import re

from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import request

from info import constants
from info import db
from info.libs.image_storage import storage
from info.models import User, House, Order
from info.utils.common import user_login
from info.utils.response_code import RET
from . import api


@api.route('/user/auth', methods=['GET','POST'])
@user_login
def func_auth():
    if not g.user:
        return jsonify(errno=RET.SESSIONERR ,errmsg="用户未登录")
    if request.method == "GET":
        data = {
            'real_name' : g.user.real_name,
            'id_card' : g.user.id_card
        }
        return jsonify(errno=RET.OK ,errmsg="OK",data=data)

    real_name = request.json.get("real_name")
    id_card = request.json.get("id_card")
    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR ,errmsg="缺少参数")
    if g.user.real_name:
        return jsonify(errno=RET.DATAEXIST ,errmsg="无法更改")

    g.user.real_name = real_name
    g.user.id_card = id_card
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="数据库存储错误")
    return jsonify(errno=RET.OK ,errmsg="OK")


@api.route("/user/houses")
@user_login
def myhouses():
    """
    我的房源
    :return:
    """
    # user_id = g.user_id
    # user_id = 7
    # User.id = 7
    # user_id = user.id
    # # user_id = user.id
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")
    houses = g.user.houses # [obj..]
    houses_list = []
    for house in houses:
        houses_list.append(house.to_basic_dict())
    print(houses_list)
    data =houses_list
    # return render_template("../../static/html/myhouse.html", data=data)
    return jsonify(errno=RET.OK, errmsg="ok", data=data)

#
# @api.route("/orders?role=landlord", methods=["GET","POST"])
# @user_login
# def accept_order(order_id):
#     "客户订单"
#
#     if request.method == "GET":
#         role = request.get_json("role")
#         if  role != "landlord":
#             return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
#         orders = g.user.orders
#         order_list = []
#         for order in orders:
#             order_list.append(order.to_dict())
#         data = order_list
#         return jsonify(errno=RET.OK, errmsg="OK", data=data)
#     elif request.method == "POST":
#         req_data = request.get_json()
#         if not req_data:
#             return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
#
#         action = req_data.get("action")
#
#         if action not in("accept", "reject"):
#             return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
#
#         try:
#             order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
#             house = order.house
#         except Exception as e:
#             current_app.logger.error(e)
#             return jsonify(errno=RET.DBERR, errmsg="无法获取订单数据")
#
#         if not order or house.user_id != g.user.id:
#             return jsonify(errno=RET.REQERR, errmsg="操作无效")
#
#         if action == "accept":
#             order.status = "WAIT_PAYMENT"
#         elif action == "reject":
#             reason = req_data.get("reason")
#             if not reason:
#                 return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
#             order.status = "REJECTED"
#             order.comment = reason
#
#             try:
#                 db.session.add(order)
#                 db.session.commit()
#             except Exception as e:
#                 current_app.logger.error(e)
#                 db.session.rollback()
#                 return jsonify(errno=RET.DBERR, errmsg="添加数据库失败")
#         return jsonify(errno=RET.OK, errmsg="OK")
#         # return render_template("lorders.html")
#


@api.route("/user", methods=["GET"])
@user_login
def user_indo():
    user = g.user
    if not user:
        return redirect("/")

    return jsonify(errno=RET.OK, errmsg="Ok", data=user.to_dict())


@api.route("/user/name",methods=["POST"])
@user_login
def user_name():
    user_id = g.user.id
    req_dict = request.get_json()
    name = req_dict.get("name")
    if name is None:
        return jsonify(errno=RET.NODATA, errmsg="昵称不能为空")

    try:
        user = User.query.filter_by(id=user_id).first()
        # 从数据中获取用户昵称
        user_name = user.name
        if user_name is not None and user_name == name:
            return jsonify(errno=RET.DATAEXIST, errmsg="用户名已存在")
    except Exception as e:
        current_app.logger.error(e)

    try:
        User.query.filter_by(id=user_id).update({"name": name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存用户昵称失败")

    return jsonify(errno=RET.OK, errmsg="修改成功", data={"name": name})


@api.route("/user/avatar", methods=["GET","POST"])
@user_login
def user_avatar():

    user = g.user
    if request.method == "GET":
        data = {
            "avatar_url": User.avatar_url
        }
        return jsonify(errno=RET.OK, errmsg="OK",data=data)

    try:
        image_data = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 将用户上传的图像 保存在七牛云上
    try:
        key = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    user.avatar_url = key

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="上传头像成功", data=constants.QINIU_DOMIN_PREFIX + key)


